<template>
  <div class="layout-nav">
    <div class="layout-nav-left">
      <div class="layout-nav-logo">
        <span class="name">{{ systemInfo?.system_name || '系统' }} </span>
        <span class="version">{{ systemInfo?.system_version|| '0.01' }}</span>
      </div>
      <div
        class="layout-nav-menu"
        :class="{ 'is-menu-nav': isMenuNav }"
        ref="menusRef"
      >
        <el-dropdown v-if="isMenuNav">
          <div class="layout-nav-menu-btn">
            <i class="icon icon-fenlei-3"></i>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <template v-for="(item, index) in menuList" :key="index">
                <el-dropdown-item
                  @click="goPath(item)"
                  v-permission="item.menu_node"
                  >{{ item.menu_name }}</el-dropdown-item
                >
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <template v-else v-for="(item, index) in menuList" :key="index">
          <div
            class="layout-nav-menu-item"
            :class="curNav == item.id ? 'active' : ''"
            v-permission="item.menu_node"
            @click="goPath(item)"
          >
            {{ item.menu_name }}
          </div>
        </template>
      </div>
    </div>
    <div class="layout-nav-right" ref="rightRef">
      <el-dropdown v-if="adminInfo">
        <div class="layout-nav-user">
          <div class="mr10 fw">
            {{ adminInfo.real_name }}
            ({{ adminInfo.account }})
          </div>
          <el-avatar shape="square" size="small" :src="adminInfo.avatar" />
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="outLogin">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div v-else>未登录</div>
    </div>
  </div>
</template>
<script lang="ts">
export default {
  name: "LayoutNav",
};
</script>
<script setup lang="ts">
import { getCurrentInstance, ref, watch, onMounted, nextTick } from "vue";
import { useAdmin, useMenus, useConfig } from "@/store";
import { logout } from "@/api/common";
import router from "@/router/index";
import { useRouter, useRoute } from "vue-router";
import system from "@/router/modules/system";
import { resourceLimits } from "worker_threads";

const emit = defineEmits(["change"]);

const MenusStore = useMenus();

const menuList = ref(MenusStore.getMenus);

const {
  proxy: { $message, $utils },
} = getCurrentInstance() as any;

const adminStore = useAdmin();

const adminInfo = adminStore.curAdmin;

const configStore = useConfig();

const systemInfo = ref(configStore.getSystemInfo);

const loadMessage = ref<any>();

const outLogin = function () {
  loadMessage.value = $message({
    duration: 0,
    message: "正在退出...",
  });
  logout().then(async (res: any) => {
    adminStore.setAdmin(null);
    adminStore.setToken("", 0);
    $utils.setStorage("token", null);
    setTimeout(() => {
      loadMessage.value.close();
      $message.success({
        message: "退出成功!",
        onClose: () => {
          toLogin();
        },
      });
    }, 500);
  });
};
const curNav = ref<number | string>(-1);

const goPath = (menu: any) => {
  curNav.value = menu.id;
  if (menu.children && Object.keys(menu.children).length > 0) {
    emit("change", menu.children);
    // 存在下级
    let itemMenu = $utils.getItemPath(menu.children);
    router.push({
      path: itemMenu.menu_path,
      query: itemMenu.url_params || {},
    });
  } else {
    emit("change", []);
    // 直接跳转指定页面
    router.push({
      path: menu.menu_path,
      query: menu.url_params || {},
    });
  }
};

const initRoute = () => {
  var _router = {
    path: router.currentRoute.value.path,
    activeMenu: router.currentRoute.value.meta.activeMenu || "",
    addon:
      router.currentRoute.value.params.addon ||
      router.currentRoute.value.meta.addon ||
      "",
  };
  if (!menuList.value || menuList.value == undefined) {
    toLogin();
    return false;
  }
  refresh(menuList.value, _router, -1);
};

//
const refresh = (data: any, _router: any, parent: number | string) => {
  try {
    data.forEach((item: any, index: any) => {
  // console.log(_router,item)
      if (item.children && item.children.length > 0) {
        refresh(item.children, _router, parent == -1 ? item.id : parent);
      } else if (_router.addon && item.menu_node == "addon") {
  console.log(_router)
        setCurNavPath(item.id, _router.addon);
        throw new Error(`End refresh addon:${_router.addon}`);
      } else if (
        item.menu_path == _router.path ||
        (_router.activeMenu != "" && item.menu_path == _router.activeMenu) ||
        $utils.getMenuString(item.menu_path) ==
          $utils.getMenuString(_router.path) ||
        $utils.getMenuActionParent(item, _router.path)
      ) {
        if (parent === -1) {
          setCurNavPath(item.id, false);
        } else {
          setCurNavPath(parent, false);
        }
        throw new Error("End refresh");
      }
    });
  } catch (e: any) {
    // if(e.message == 'End Loop') throw e
  }
};

const addonMenus = ref<any>(MenusStore.getAddonMenus);

const setCurNavPath = (id: number | string, addon: string | unknown) => {
  curNav.value = id;
  menuList.value.forEach((item: any) => {
    if (id === item.id) {
      var children = item.children || [];
      if (typeof addon == "string") {
        children = addonMenus.value[addon];
      }
      emit("change", children);
    }
  });
};

const toLogin = () => {
  router.replace({
    path: "/login",
    query: {
      redirect: router.currentRoute.value.fullPath,
    },
  });
};

const screenWidth = ref();

const menusRef = ref<HTMLElement>();

const rightRef = ref<HTMLElement>();

// 是否收起
const isMenuNav = ref<boolean>(false);

watch(
  () => configStore.getSystemInfo,
  (val) => {
    systemInfo.value = val;
  },
  { deep: true }
);

watch(
  () => screenWidth.value,
  (n: any, o) => {
    var menuWidth = menusRef.value?.clientWidth || 0;
    var rightWidth = menusRef.value?.clientWidth || 0;
    if (menuWidth <= n - rightWidth - 256) {
      isMenuNav.value = true;
    } else {
      isMenuNav.value = false;
    }
  },
  { deep: true }
);

watch(
  () => router.currentRoute.value,
  (val) => {
    initRoute();
  },
  { deep: true }
);

watch(
  () => MenusStore.getMenus,
  (val) => {
    menuList.value = val;
    nextTick(() => {
      initRoute();
    });
  },
  { deep: true }
);

onMounted(() => {
  if (adminInfo == null || !adminInfo) {
    toLogin();
  }
  screenWidth.value = document.body.clientWidth;
  window.onresize = () => {
    return (() => {
      screenWidth.value = document.body.clientWidth;
    })();
  };
  nextTick(() => {
    initRoute();
  });
});
</script>
<style scoped>
.layout-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--el-border-color-lighter);
  height: 50px;
}
.layout-nav .layout-nav-left {
  width: calc(100% - 300px);
  display: flex;
}
.layout-nav .layout-nav-right {
  margin-right: 20px;
}
.layout-nav .layout-nav-logo {
  width: 176px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.layout-nav .layout-nav-logo .name {
  font-size: 16px;
  font-weight: bold;
}
.layout-nav .layout-nav-logo .version {
  margin-left: 5px;
  font-size: 12px;
  color: var(--base-grey);
}
.layout-nav .layout-nav-menu {
  display: flex;
  overflow: hidden;
  flex: 1;
  align-items: center;
  -webkit-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}
.layout-nav-menu-btn {
  width: 40px;
  text-align: center;
  height: 40px;
  line-height: 40px;
  cursor: pointer;
}
.layout-nav-menu-btn:hover {
  color: var(--base-default);
}
.layout-nav .layout-nav-menu-item {
  padding: 0 12px;
  font-size: var(--base-size);
  cursor: pointer;
  height: 30px;
  line-height: 30px;
  user-select: none;
  border-radius: 2px;
}
.layout-nav .layout-nav-menu-item:hover {
  background: var(--el-color-primary-light-9);
  color: var(--base-default);
}
.layout-nav .layout-nav-menu-item.active {
  color: var(--base-default);
}
.layout-nav-user {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
}
</style>